package com.lxy.elasticsearch200.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import com.lxy.elasticsearch200.base.result.Result;
import com.lxy.elasticsearch200.dto.AddStudentDto;
import com.lxy.elasticsearch200.dto.StudentListDto;
import com.lxy.elasticsearch200.entity.ExamStudent;
import com.lxy.elasticsearch200.repository.ExamStudentRepository;
import com.lxy.elasticsearch200.service.ExamStudentService;
import com.lxy.elasticsearch200.vo.ListVo;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.PipelineAggregatorBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 学生业务层实现
 * </p>
 *
 * @author Administrator
 * @since 2024/11/16
 */
@Service
public class ExamStudentServiceImpl implements ExamStudentService {

    private ExamStudentRepository examStudentRepository;

    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Transactional
    @Override
    public Result<Boolean> add(AddStudentDto addStudentDto) {
        for (int i = 0; i <= 1000; i++) {
            List<ExamStudent> list = new ArrayList<>();
            for (int j = 0; j <= 1000; j++) {
                ExamStudent examStudent = new ExamStudent();
                examStudent.setId(IdUtil.getSnowflake().nextId());
                examStudent.setStuName("i=" + i + ",j=" + j);
                examStudent.setStuNo(IdUtil.fastSimpleUUID());
                examStudent.setIdCard(IdUtil.fastSimpleUUID());
                while (true) {
                    examStudent.setClazzLevel(RandomUtil.randomInt(9));
                    if (examStudent.getClazzLevel() > 0) {
                        break;
                    }
                }
                while (true) {
                    examStudent.setClazzNo(RandomUtil.randomInt(30));
                    if (examStudent.getClazzNo() > 0) {
                        break;
                    }
                }
                examStudent.setClazzName("[" + examStudent.getClazzLevel() + "]年级[" + examStudent.getClazzNo() + "]");
                list.add(examStudent);
            }
            examStudentRepository.saveAll(list);
        }
        return Result.success(true);
    }

    @Override
    public Result<List<ListVo>> list(StudentListDto studentListDto) {
        List<ListVo> list = new ArrayList<>();

        // 创建查询请求
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        // 设置查询条件（可以根据需要修改）
        queryBuilder.withQuery(QueryBuilders.matchAllQuery());

        // 设置分组条件
        queryBuilder.addAggregation(AggregationBuilders.terms("group_by_clazz_name").field("clazz_name").size(100));
        queryBuilder.addAggregation(AggregationBuilders.count("count_clazz_name").field("clazz_name"));

        // 设置分页参数
        queryBuilder.withPageable(PageRequest.of(studentListDto.getPage(), studentListDto.getSize()));

        // 构建查询对象
        NativeSearchQuery searchQuery = queryBuilder.build();

        // 执行查询并获取结果
        SearchHits<ExamStudent> searchHits = elasticsearchRestTemplate.search(searchQuery, ExamStudent.class);

        // 获取总记录数
        long totalRecords = searchHits.getTotalHits();

//        // 获取分组结果
//        Terms groupByResult = searchHits.getAggregations().get("group_by_field");
//        for (Terms.Bucket bucket : groupByResult.getBuckets()) {
//            String key = bucket.getKeyAsString(); // 分组键
//            long docCount = bucket.getDocCount(); // 该分组下的文档数量
//            System.out.println("Key: " + key + ", Doc Count: " + docCount);
//        }

        // 打印总记录数
        System.out.println("Total Records: " + totalRecords);

        return Result.success(list);
    }

//    public void getExamStudentData() {
//        // 创建搜索请求
//        SearchRequest searchRequest = new SearchRequest("exam_student");
//        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//        searchSourceBuilder.size(0); // 不需要实际的文档内容，只需要聚合结果
//
//        // 添加按班级名称分组的聚合
//        TermsAggregationBuilder groupByClazzNameAggs = AggregationBuilders.terms("group_by_clazz_name")
//                .field("clazz_name")
//                .size(10000000);
//
//        // 添加桶排序子聚合
//        groupByClazzNameAggs.subAggregation(AggregationBuilders.bucketSort("page_group_by_clazz_name", "_count")
//                .order(org.elasticsearch.search.aggregations.bucket.terms.Terms.Order.count(false))
//                .from(0).size(10000000));
//
//        searchSourceBuilder.aggregation(groupByClazzNameAggs);
//        searchRequest.source(searchSourceBuilder);
//
//        try {
//            // 执行搜索
//            SearchResponse searchResponse = elasticsearchRestTemplate.getClient().search(searchRequest, RequestOptions.DEFAULT);
//
//            // 解析聚合结果
//            System.out.println(searchResponse);
//            // 这里你可以根据需要进一步解析和处理响应结果
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    @Autowired
    public void setExamStudentRepository(ExamStudentRepository examStudentRepository) {
        this.examStudentRepository = examStudentRepository;
    }

    @Autowired
    public void setElasticsearchRestTemplate(ElasticsearchRestTemplate elasticsearchRestTemplate) {
        this.elasticsearchRestTemplate = elasticsearchRestTemplate;
    }

}
